<script setup lang="ts">
import { request } from '@/apis';
import { closeDialog, closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import base64ToBlob from 'b64-to-blob'
// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)

const actions = [ {name:'相册'},{name:'拍照'}]

const profile = ref<ProfileInfo>({} as ProfileInfo)

// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
  let dataStr = ''
  if (i === 0) {
    // 相册上传
    const dataStr = await mk.pickerPhoto()
    await onUpdateAvatar(dataStr)
  } else if (i === 1) {
    // 拍照上传
    const dataStr = await mk.pickerCamera()
    await onUpdateAvatar(dataStr)
  }
  console.log('图片数据', dataStr)
}
// 1.3 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatarSheet.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    // 把 base64 字符串转换
    const image = base64ToBlob(data, 'image/jpeg')
    // 后端要求传递 FormData 数据
    const fd = new FormData()
    // 按文档要求准备参数
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>(
      'member/profile/avatar',
      fd,
    )
    console.log('上传头像成功', res.data)
    // 更新表单的数据
    profile.value.avatar = res.data.result.avatar
    // 查询原生鸿蒙的用户信息
    const user = mk.queryUser()
    // 更新原生鸿蒙的用户信息
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch {
    showToast({ message: '上传失败' })
  }
}
// 生日选择器开关
const showBirthdayPopup = ref(false)
// date-picker 组件的日期格式为数组 ['YYYY','MM','DD']
const birthday = ref(['','',''])
// 生日选择器回调
const onChangeBirthday = (date:{ selectedValues:string[]})=>{
  console.log('生日选择器回调')
  showBirthdayPopup.value = false
   // 把 selectedValues 转换成字符串，用于后端表单提交
  profile.value.birthday = date.selectedValues.join('-')
}


//  选择职业数据
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
// 是否显示职业弹窗
const showProfessionPopup = ref(false)


const onChangeProfession = (data:{selectedValues:string[]})=>{
  console.log('变化',data.selectedValues)
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}
// 是否显示地区弹窗
const showAreaPopup = ref(false)
const AreaList = ref<AreaColumns>({
  province_list: {
    110000: '北京',
    120000: '天津',
  },
  city_list: {
    110100: '北京市',
    120100: '天津市',
  },
  county_list: {
    110101: '东城区',
    110102: '西城区',
    120101: '天津1区',
    120102: '天津2区',
  },
})
onMounted(async ()=>{
  const res = await mk.getAreaColumns()
  AreaList.value = res
})
const onChangeArea = (data:{
  selectedValues:string[],
  selectedOptions:{text:string}[]})=>{
  showAreaPopup.value = false
  // 处理数据
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]
  
  profile.value.fullLocation = data.selectedOptions.map(item=>item.text).join('')
  
  console.log('地区选择回调')
  
}


onMounted(async ()=>{
  // 加载中
  showLoadingToast({message:'加载中',duration:0,forbidClick:true})
  // 获取用户信息 
  const res = await request.get('/member/profile') 
  // 保存数据
  profile.value = res.data.result
   // 后端数据格式与前端组件格式不一致，需要按组件要求转换数据格式
  // 转换保存生日数据，按 date-picker 要求准备默认值展示
  birthday.value = profile.value.birthday.split('-')
  // 关闭弹窗
  closeToast()
  
})

const loading = ref(false)
const submit = async ()=>{
  loading.value = true
  const res = await request.put<MkResponse<ProfileInfo>>('/member/profile',profile.value)
  loading.value = false
  const user = mk.queryUser()
  user.avatar = profile.value.avatar
  user.nickname = profile.value.nickname
  mk.updateUser(user)
  showToast({message:res.data.msg})  
  
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <van-action-sheet 
    v-model:show="showAvatarSheet" 
    :actions=actions
    @select="onSelectAvatar" 
    cancel-text="取消" 
    :style="{ paddingBottom: '20px' }">
  </van-action-sheet>
    <!-- 中间表单部分 -->
    
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" readonly placeholder="请选择日期" @click="showBirthdayPopup = true"  v-model="profile.birthday"></van-field>
      <van-popup v-model:show="showBirthdayPopup" round position="bottom">
        <van-date-picker
        v-model="birthday"
        title="选择日期"
        @cancel="showAvatarSheet = false" 
        @confirm="onChangeBirthday"
        :min-date="new Date('1980-01-01')"
        :max-date="new Date()"
        
        ></van-date-picker>
      </van-popup>
      <van-field v-model="profile.fullLocation" @click="showAreaPopup = true" label="所在地" readonly placeholder="请选择所在地"></van-field>
      <!-- 打开地区弹窗 -->
       <van-popup v-model:show="showAreaPopup" round position="bottom">
          <van-area @cancel="showAreaPopup = false"  :area-list="AreaList" @confirm="onChangeArea" title="请选择省市区"  />
       </van-popup>
      
      <van-field @click="showProfessionPopup = true" label="职业" readonly placeholder="请选择职业" v-model="profile.profession"></van-field>
      <!-- 打开选择职业弹层 -->
      <van-popup v-model:show="showProfessionPopup" round position="bottom" >
        <van-picker title="请选择职业" :columns="columns" @confirm="onChangeProfession" @cancel="showProfessionPopup = false" />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="submit" :loading="loading">
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>